package com.seckill.goods.dispatcher;

import cn.hutool.core.collection.CollUtil;
import com.seckill.goods.pojo.Sku;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 这个实现类的作用是实现商品库存的redis缓存
 */
@Component
@RequiredArgsConstructor
public class CanalSkuDataDispatcher implements CanalDataDispatcher<Sku> {

    @Autowired
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void update(List<Sku> skuList) {
        if (CollUtil.isEmpty(skuList)) {
            return;
        }
        //只缓存秒杀商品的库存
        skuList.stream()
                .filter(sku -> sku.getStatus() == 2)
                .forEach(sku -> {
                    //更新操作
                    String key = "CAT:" + sku.getCategory3Id() + ":" + sku.getId();
                    //缓存价格
                    stringRedisTemplate.opsForHash().put(key, "PC", sku.getSeckillPrice().toString());
                    //缓存数量
                    stringRedisTemplate.opsForHash().put(key, "CN", sku.getSaleNum().toString());
                });

    }

    @Override
    public void delete(List<Sku> skuList) {
        if (CollUtil.isEmpty(skuList)) {
            return;
        }
        //只缓存秒杀商品的库存
        skuList.stream()
                .filter(sku -> sku.getStatus() == 2)
                .forEach(sku -> {
                    //删除操作
                    String key = "CAT:" + sku.getCategory3Id() + ":" + sku.getId();
                    stringRedisTemplate.delete(key);
                });
    }

    @Override
    public void insert(List<Sku> skuList) {
        if (CollUtil.isEmpty(skuList)) {
            return;
        }
        //只缓存秒杀商品的库存
        skuList.stream()
                .filter(sku -> sku.getStatus() == 2)
                .forEach(sku -> {
                    //更新操作
                    String key = "CAT:" + sku.getCategory3Id() + ":" + sku.getId();
                    //缓存价格
                    stringRedisTemplate.opsForHash().put(key, "PC", sku.getSeckillPrice().toString());
                    //缓存数量
                    stringRedisTemplate.opsForHash().put(key, "CN", sku.getSaleNum().toString());
                });
    }
}
